package org.eclipse.football;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class KickerStatsServlet extends HttpServlet implements Servlet {
	// Override doPost function
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Read in information submitted by form
		String pat_raw = request.getParameter("pat");
		String fg0_raw = request.getParameter("fg0");
		String fg1_raw = request.getParameter("fg1");
		String fg2_raw = request.getParameter("fg2");
		String misses_raw = request.getParameter("misses");
		
		// Convert all input values to integers
		int pat = stringToInt(pat_raw);
		int fg0 = stringToInt(fg0_raw);
		int fg1 = stringToInt(fg1_raw);
		int fg2 = stringToInt(fg2_raw);
		int misses = stringToInt(misses_raw);
		
		// Obtain existing league
		League league = (League) request.getSession(true).getAttribute("league");
		
		// Obtain existing team
		Team team = (Team) request.getSession(true).getAttribute("team");
		
		// Obtain existing kicker
		Kicker player = (Kicker) request.getSession(true).getAttribute("kicker");
		
		// Add new stats to players old stats and set them in player
		player.setPat(pat+player.getPat());
		player.setFg0(fg0+player.getFg0());
		player.setFg1(fg1+player.getFg1());
		player.setFg2(fg2+player.getFg2());
		player.setMisses(misses+player.getMisses());

		// Set player back to null
		player = null;
		
		// Write the state of the league out to a file
		league.writeState();
		
		// Set league in the session
		request.getSession().setAttribute("league", league);
		
		// Set team in the session
		request.getSession().setAttribute("team", team);
		
		// Set player in the session
		request.getSession().setAttribute("kicker", player);
		
		// Set off and def as null in the session
		request.getSession().setAttribute("off", null);
		request.getSession().setAttribute("def", null);
		
		// Forward control back to stats.jsp
		getServletContext().getRequestDispatcher("/stats.jsp").forward(request, response);
		
		// TODO Auto-generated method stub
		//super.doPost(request, response);
	}

	// Define a wrapper for Integer.parseInt function
	int stringToInt(String in){
		// Check if input string is blank or null
		if(in == null || in.equalsIgnoreCase("")){
			// If so return 0
			return 0;
		}
		
		// Else convert string to int
		else{
			return Integer.parseInt(in);
		}
	}
}

